import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2btrailer/b2btrailerselfpickupsubmitscreen.dart';
import 'package:opene/ui/b2btrailer/b2btrailermodel.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailermodel.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/ui/cms/cmsmodel.dart';
import 'package:opene/ui/fbapick/fbapickmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class CMSOBLPNSubmitScreen extends StatelessWidget {
  CMSOBLPN cmsoblpn;

  CMSOBLPNSubmitScreen({this.cmsoblpn});

  @override
  Widget build(BuildContext context) {
    return CMSOBLPNSubmitScreenPage(cmsoblpn: cmsoblpn);
  }
}

class CMSOBLPNSubmitScreenPage extends StatefulWidget {
  CMSOBLPN cmsoblpn;

  CMSOBLPNSubmitScreenPage({this.cmsoblpn});

  @override
  _CMSOBLPNSubmitPageState createState() => _CMSOBLPNSubmitPageState(cmsoblpn: cmsoblpn);
}

class _CMSOBLPNSubmitPageState extends BaseState<CMSOBLPNSubmitScreen> {
  CMSOBLPN cmsoblpn;

  List<CMSOBLPNDetails> inList = new List();//未扫描
  List<CMSOBLPNDetails> outList = new  List();//已扫描

  List<CMSOBLPNDetails> data = new List();
  PhotoBean bolPhoto = new PhotoBean();
  _CMSOBLPNSubmitPageState({this.cmsoblpn});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "OutBoundLPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    next="Submit";
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        outLoadingV2Detail();
      });
    });
  }
  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    bolPhoto.image = image;
    fileUpload("cmsoblpn", "cmsoblpn", image, "close", 0, 0, false, false);
  }
  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "Dest: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "Expected: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "BOL NO: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      cmsoblpn == null ? "" : Utils.getStringisEmpty(cmsoblpn.destination),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      cmsoblpn == null ? "" : Utils.getStringisEmpty(cmsoblpn.deliveryDate),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      cmsoblpn == null ? "" : Utils.getStringisEmpty(cmsoblpn.bolNumber),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                outLoadingLoading(text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      outLoadingLoading(text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "scan inbound lpn barcode",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 1) {
                      return;
                    }

                    setState(() {
                      type = 1;
                      if(data==null){
                        data = new List();
                      }
                      data.clear();
                      outLoadingV2Detail();
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'LPN List(${inList.length})',
                      style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 2) {
                      return;
                    }
                    setState(() {
                      type = 2;
                      if(data==null){
                        data = new List();
                      }
                      data.clear();
                      outLoadingV2Detail();
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Lpn Out(${outList.length})',
                      style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(child: setListView()),
          SizedBox(
            height: 5,
          ),
          setPhotoView("After Loading:  ", 0, bolPhoto),
          SizedBox(
            height: 5,
          ),
        ],
      ),
    );
  }
  Container setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Container(
      height: 70,
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  hintText,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                ),
              ],
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Row(
                children: [
                  Container(
                    width: 70,
                    height: 70,
                    child: Stack(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            // 请求焦点
                            FocusScope.of(context).requestFocus(FocusNode());
                            ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                          },
                          child: photoBean.image == null
                              ? (photoBean.urlImg == null
                              ? Image.asset(
                            'assets/images/add.png',
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          )
                              : Image.network(
                            Constants.baseImgUrl + photoBean.urlImg,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ))
                              : Image.file(
                            photoBean.image,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Visibility(
                          visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                          child: Positioned(
                            top: 2.0,
                            right: 2.0,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  photoBean.urlImg = null;
                                  photoBean.image = null;
                                });
                              },
                              child: Image.asset(
                                'assets/images/ic_delete_menu.png',
                                width: 15,
                                height: 15,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }
  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        CMSOBLPNDetails trailerOBLPN = data[index];
        return Column(
          children: [
            Visibility(
                visible: index==0?true:false,
                child: SizedBox(height: 5,)),
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Text(
                      Utils.getStringisEmpty(trailerOBLPN.palletLpn),
                      style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                    )),
                Expanded(
                    flex: 1,
                    child: Row(
                      children: [
                        Expanded(
                            flex: 1,
                            child: Text(
                              Utils.getStringisEmpty(trailerOBLPN.location),
                              style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                            )),
                        Visibility(
                          visible: type == 2 ? true : false,
                          child: GestureDetector(
                            onTap: () {
                              removeLpn(Utils.getStringisEmpty(trailerOBLPN.palletLpn));
                            },
                            child: Icon(
                              Icons.delete,
                              size: 20,
                              color: MyAppTheme.grey,
                            ),
                          ),
                        ),
                      ],
                    ),
                ),

              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void outLoadingV2Detail() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, "${Constants.outLoadingV2Detail}/${Utils.getStringisInteger(cmsoblpn.id)}");

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      CMSOBLPNDetailsBase cmsoblpnDetailsBase = CMSOBLPNDetailsBase.fromJson(baseResponse.data);
      setOBLPNDetails(cmsoblpnDetailsBase);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
  void setOBLPNDetails(CMSOBLPNDetailsBase cmsoblpnDetailsBase) async {
    setState(() {
      if(!Utils.isEmpty(cmsoblpnDetailsBase.bol)){
        bolPhoto.urlImg = cmsoblpnDetailsBase.bol;
      }

      List<CMSOBLPNDetails> lpnList = cmsoblpnDetailsBase.lpnList;


      if(lpnList==null){
        return;
      }


      inList.clear();
      outList.clear();
      for (CMSOBLPNDetails cmsoblpnDetails in lpnList) {
        if (0 == Utils.getIntegerisEmpty(cmsoblpnDetails.isPick)) {
          inList.add(cmsoblpnDetails);
        } else {
          outList.add(cmsoblpnDetails);
        }
      }
      if(data==null){
        data = new List();
      }
      data.clear();
      if (type == 1) {
        data.addAll(inList);
      } else {
        data.addAll(outList);
      }

    });
  }
  void removeLpn(String lpn) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "Delete...");
    } catch (e) {
      e.toString();
    }
    CMSOBLPNTrailerQr cmsoblpnTrailerQr = new CMSOBLPNTrailerQr();
    cmsoblpnTrailerQr.orderId = (cmsoblpn.id);
    cmsoblpnTrailerQr.palletLpn = lpn;
    String json = jsonEncode(cmsoblpnTrailerQr);
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.outLoadingV2Remove,method: BaseMethod.post,data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      CMSOBLPNDetailsBase cmsoblpnDetailsBase = CMSOBLPNDetailsBase.fromJson(baseResponse.data);
      setOBLPNDetails(cmsoblpnDetailsBase);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void outLoadingLoading(String barcodeStr) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "Check...");
    } catch (e) {
      e.toString();
    }
    CMSOBLPNTrailerQr containerOBLPNTrailerQr = new CMSOBLPNTrailerQr();
    containerOBLPNTrailerQr.orderId = cmsoblpn.id;
    containerOBLPNTrailerQr.palletLpn =barcodeStr;
    String json = jsonEncode(containerOBLPNTrailerQr);
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.outLoadingV2Loading, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      CMSOBLPNDetailsBase cmsoblpnDetailsBase = CMSOBLPNDetailsBase.fromJson(baseResponse.data);
      setOBLPNDetails(cmsoblpnDetailsBase);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
  void outLoadingSubmit() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "Submit...");
    } catch (e) {
      e.toString();
    }
    CMSOBLPNSubmitQr unloadQr = new CMSOBLPNSubmitQr();
    unloadQr.orderId = (cmsoblpn.id);
    unloadQr.bol = (bolPhoto.urlImg);
    String json = jsonEncode(unloadQr);
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.outLoadingV2Submit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    bolPhoto.urlImg = path;

    if(isSubmit){
      outLoadingSubmit();
    }
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (bolPhoto.image==null) {
      Toast.show("Please add bol photos", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (outList == null || outList.length == 0) {
      Toast.show("Please add PalletLPN", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    if ((bolPhoto.image != null) && Utils.isEmpty(bolPhoto.urlImg)) {
      fileUpload("cmsoblpn", "cmsoblpn", bolPhoto.image, "close", 0, 0, false, true);
      return;
    }
    outLoadingSubmit();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
